package net.ideapad.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.ideapad.data.Group;
import net.ideapad.data.User;
import net.ideapad.hibernate.HibernateSessionFactory;
import net.ideapad.struts.form.CreateGroupForm;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;

/**
 * Action class to process the creation of a group.
 * 
 * MyEclipse Struts Creation date: 12-14-2009
 * 
 * XDoclet definition:
 * 
 * @struts.action path="/createGroup" name="createGroupForm"
 *                input="/form/createGroup.jsp" scope="request" validate="true"
 * 
 * @struts.action-forward name="viewGroups" path="/form/viewGroups.jsp"
 */
public class CreateGroupAction extends Action {
	/**
	 * Creates a new group with the user provided Group Name and Parent Group.
	 * Input is done through the form.
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		CreateGroupForm createGroupForm = (CreateGroupForm) form;

		Session session = HibernateSessionFactory.getSession();

		Integer userID = (Integer) request.getSession().getAttribute("userID");
		Integer groupID = createGroupForm.getParentGroupID();

		session.beginTransaction();
		User u = (User) session.createQuery("from User u where u.userId = :id").setInteger("id", userID).uniqueResult();

		// The new group
		Group newGroup = new Group();

		// Get the parent group
		if (groupID != null) {
			Group g = (Group) session.createQuery("from Group g where g.groupId = :id").setInteger("id", groupID).uniqueResult();
			newGroup.setParentGroup(g);
		}

		newGroup.setGroupName(createGroupForm.getGroupName());
		newGroup.getModerators().add(u);
		newGroup.getUsersInGroup().add(u);

		// Save the group
		session.saveOrUpdate(newGroup);
		session.getTransaction().commit();
		HibernateSessionFactory.closeSession();

		// Return the View Groups page.
		return (new ViewGroupsAction()).execute(mapping, null, request, response);
	}
}